<?php

namespace Trawind\Basics;

use Prettus\Repository\Eloquent\BaseRepository;
use Trawind\Basics\Enums\BusinessCode;
use Trawind\Basics\Enums\SystemConstant;
use Trawind\ConfigCenter\Helpers\ConfigHelper;
use Trawind\Extension\Models\Deploy\BusinessType;
use Trawind\Extension\Models\Deploy\BusinessTypeQueryer;
use Trawind\Helpers\HttpClientHelper;

abstract class TrawindRepository extends BaseRepository
{

    public $skipPresenter = true;

    protected $fieldSearchable = ['id'];

    public function view(bool $skipPresenter = false, ?int $limit = null, $columns = ['*'])
    {
        is_null($limit) and $limit = request('pageSize');

        $isPaginate = is_null($limit) || $limit > 0;
        if ($isPaginate && is_null($limit)) {
            $limit = ConfigHelper::resolve('page_size');
        }

        $this->skipPresenter($skipPresenter);
        return $isPaginate ? $this->paginate($limit, $columns) : $this->all($columns);
    }


    public function skipFind($id, bool $skipPresenter = false, $columns = ['*'])
    {
        return $this->skipPresenter($skipPresenter)->find($id, $columns);
    }


    public function skipCreate(array $attributes, bool $skipPresenter = false)
    {
        return $this->skipPresenter($skipPresenter)->create($attributes);
    }


    public function skipUpdate(array $attributes, $id, bool $skipPresenter = false)
    {
        return $this->skipPresenter($skipPresenter)->update($attributes, $id);
    }

    public function getListByField(array $values, $field, bool $isColumnData = true)
    {
        if (empty($values = array_unique($values))) {
            return [];
        }

        $result = $this->model()::whereIn($field, $values)->get()->toArray();
        $data = $isColumnData ? array_column($result, null, $field) : $result;
        return $data;
    }


    public function getListById(array $ids, bool $isColumnData = true)
    {
        return $this->getListByField($ids, 'id', $isColumnData);
    }


    public function batchUpdateStatus(array $ids, int $status_type_id)
    {
        $result = $this->findWhereIn('id', $ids);

        foreach ($result['data'] as &$item) {
            $item['message'] = ___(BusinessCode::UPDATED_OK());
            if ($item['status_type_id'] == SystemConstant::INVALID) {
                $ids = array_merge(array_diff($ids, [$item['id']]));
                build_friendly_tips($item, ___('exception.in_invalid'), $this->businessType ?? null);
            }
        }

        unset($item);
        $this->makeModel()->whereIn('id', $ids)->update(compact('status_type_id'));
        $this->makeModel()->writeLog($ids);
        return $result;
    }


    public function batchDelete(array $ids)
    {
        $result = $this->findWhereIn('id', $ids);

        foreach ($result['data'] as &$item) {
            $item['message'] = ___(BusinessCode::DELETED_OK());
        }

        $this->makeModel()->whereIn('id', $ids)->delete();
        $this->makeModel()->writeLog($ids);
        return $result;
    }

    public function remoteSearchHandle($model)
    {
        $businessTypeId = $model->businessType;
        $queryers = BusinessTypeQueryer::with('localField')
            ->where('business_type_id', $businessTypeId)
            ->whereIn('relation_business_type_id', explode(',', request('remote')))
            ->get()
            ->toArray();

        $remoteParam = HttpClientHelper::getRemoteParam();
        foreach ($queryers as $queryer) {
            if (in_array($relation_business_type_id = $queryer['relation_business_type_id'], $remoteParam['remote'])) {
                $result = BusinessType::getEloquentById($relation_business_type_id)
                        ->getListBySearch([
                            'include' => $remoteParam['include'][$relation_business_type_id] ?? '',
                            'with' => $remoteParam['with'][$relation_business_type_id] ?? '',
                            'search' => $remoteParam['search'][$relation_business_type_id] ?? '',
                            'searchFields' => $remoteParam['searchFields'][$relation_business_type_id] ?? '',
                            'searchJoin' => 'and',
                            'orderBy' => $remoteParam['orderBy'][$relation_business_type_id] ?? '',
                            'sortedBy' => $remoteParam['sortedBy'][$relation_business_type_id] ?? '',
                            'pageSize' => 0,
                        ])['data'] ?? [];
                $ids = array_column($result, 'id');

                $search = array_filter(explode(';', request('search')));
                $search[] = $queryer['local_field']['name'].':'.join(',', $ids);

                $searchFields = array_filter(explode(';', request('searchFields')));
                $searchFields[] = $queryer['local_field']['name'].':in';
                request()['search'] = join(';', $search);
                request()['searchFields'] = join(';', $searchFields);
            }
        }
    }

}